<?php
/**
 * #Celebrate Shieh
 *             ,%%%%%%%%,
 *           ,%%/\%%%%/\%%
 *          ,%%%\c "" J/%%%
 * %.       %%%%/ o  o \%%%
 * `%%.     %%%%    _  |%%%
 *  `%%     `%%%%(__Y__)%%'
 *  //       ;%%%%`\-/%%%'
 * ((       /  `%%%%%%%'
 *  \\    .'          |
 *   \\  /       \  | |
 *    \\/         ) | |
 *     \         /_ | |__
 *     (___________))))))) 攻城湿
 *
 *        _       _
 * __   _(_)_   _(_) __ _ _ __
 * \ \ / / \ \ / / |/ _` |'_ \
 *  \ V /| |\ V /| | (_| | | | |
 *   \_/ |_| \_/ |_|\__,_|_| |_|
 */

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use App\User;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * @param Request $request
     *登陆
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Symfony\Component\HttpFoundation\Response|void
     * @throws \Illuminate\Validation\ValidationException
     */
    public function login( Request $request )
    {
        $this->validateLogin($request);

        $where = function ( $query ) use ( $request ) {
            $query->where('is_show', 1);
            $query->where('name', $request->username)->orWhere('email', $request->username)->orWhere('phone', $request->username);
        };
        $user  = User::where($where)->first();
        if ( ! $user ) return back()->with('error', '抱歉，此用户名未注册');
        switch ( $user->static ) {
            case 2:
                return back()->with('error', '抱歉，此用户名被禁用');
                break;
            case 3:
                return back()->with('error', '此用户名不存在');
                break;
        }
        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.

        if ( $this->hasTooManyLoginAttempts($request) ) {
            $this->fireLockoutEvent($request);
            return $this->sendLockoutResponse($request);
        }

        if ( $this->attemptLogin($request) ) return $this->sendLoginResponse($request);


        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);

    }

    /**
     * 多字段登录
     *
     * @param Request $request
     *多账户登陆
     *
     * @return bool
     */
    public function attemptLogin( Request $request )
    {
        $name     = $request->input('username');
        $password = $request->input('password');
        // 验证用户名登录方式
        $usernameLogin = $this->guard()->attempt([
            'name'     => $name,
            'password' => $password,
        ], 1);
        if ( $usernameLogin ) return TRUE;
        // 验证邮箱登录方式
        $emailLogin = $this->guard()->attempt([
            'email'    => $name,
            'password' => $password,
        ], 1);
        if ( $emailLogin ) return TRUE;
        //手机号登陆方式
        $phoneLogin = $this->guard()->attempt([
            'phone'    => $name,
            'password' => $password,
        ], 1);
        if ( $phoneLogin ) return TRUE;
        return FALSE;
    }

    /**
     * Validate the user login request.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return void
     *验证格式
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function validateLogin( Request $request )
    {
        $this->validate($request, [
            'captcha'         => 'captcha|required',
            $this->username() => 'required|string|max:30',
            'password'        => 'required|string',
        ], [
            'captcha.captcha'               => '验证码不正确',
            'captcha.required'              => '验证码必须填写',
            $this->username() . '.required' => '用户名必须填写',
            $this->username() . '.string'   => '用户名必须是字符串',
            $this->username() . '.max'      => '用户名不能大于30字符',
            'password.required'             => '密码必须填写',
            'password.string'               => '密码必须是字符串',
        ]);
    }

    /**
     * Get the login username to be used by the controller.
     *
     * @return string
     */
    public function username()
    {
        return 'username';
    }

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

}
